package com.auto.common;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import com.auto.base.mapper.BaseMapper;
import com.auto.base.pojo.SysUser;
import com.base.callback.QueryCallBack;
import com.base.common.CommonConstants;
import com.base.common.DataTableNormalDatagrid;
import com.base.common.Datagrid;
import com.base.common.DateEditor;
import com.base.common.NormalDatagrid;
import com.base.common.RequestParameters;
import com.base.util.JUtil;
import com.base.util.MapUtils;
import com.base.util.MapperUtil;
import com.base.util.Page;

import net.sf.json.JSONObject;





@Controller
@RequestMapping("/baseAction")
public class BaseController {

	//protected Map<String,Object> $data = new HashMap<String,Object>();
	protected static final String mDataProp = "mDataProp";
	private BaseMapper baseMapper;

	public BaseMapper getBaseMapper() {
		return baseMapper;
	}

	public void setBaseMapper(BaseMapper baseMapper) {
		this.baseMapper = baseMapper;
	}

	protected Object setResult(String msg,int state,Object data){
		Map<String,Object> $data  = new HashMap<String,Object>();
		$data.put(CommonConstants.SIGN_RTN_STATTE, state);
		$data.put(CommonConstants.SIGN_RTN_MSG,msg);
		if(null!=data){
			$data.put(CommonConstants.SIGN_RTN_DATA, data);
		}
		return $data;
	}

	protected Object setSuccess(String msg,Object data){
		return setResult(msg,CommonConstants.STATE_SUCCESS,data);
	}

	protected Object setSuccess(String msg){
		return setSuccess(msg,null);
	}

	protected Object setFail(String msg,Object data){
		return setResult(msg,CommonConstants.STATE_FAIL,data);
	}

	protected Object setFail(String msg){
		return setFail(msg,null);
	}

	protected Object setException(String msg,Object data){
		return setResult(msg,CommonConstants.STATE_EXCEPTION,data);
	}

	protected Object setException(String msg){
		return setException(msg,null);
	}

	protected SessionInfo getSessionInfo(HttpServletRequest request){
		Object sessionObject = JUtil.getSessionObject(request);
		SessionInfo sessionInfo = (SessionInfo)sessionObject;
		return sessionInfo;
	}

	protected SysUser getLoginSysUser(HttpServletRequest request){
		SessionInfo sessionInfo =getSessionInfo(request);
		return sessionInfo.getSysUser();
	}

	@InitBinder  
	protected void initBinder(HttpServletRequest request,  
			ServletRequestDataBinder binder) throws Exception {  
		//对于需要转换为Date类型的属性，使用DateEditor进行处理  
		binder.registerCustomEditor(Date.class, new DateEditor());  
	}  

	/**
	 * 根据代理bean查询集合
	 * @return
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws NoSuchMethodException 
	 * @throws IllegalArgumentException 
	 * @throws SecurityException 
	 */
	public Object  list (final RequestParameters requestParameters,HttpServletRequest request) throws Exception {
		Map<String,Object> queryMap = requestParameters.getQueryProxy();
		if(JUtil.isNULL(queryMap)){
			queryMap = new HashMap<String,Object>();
		}
		Page paging = null;
		if(requestParameters.getIsNonPage()==0){
			if(requestParameters.getComp() == 1){
				paging = Page.getInstance(requestParameters.getPage()-1,requestParameters.getRows());
			}else{
				paging = Page.getInstance_(requestParameters.getiDisplayStart(),requestParameters.getiDisplayLength());
			}
		}

		String sort = requestParameters.getSort();
		if(requestParameters.getComp() != 1){
			if(null != requestParameters.getiSortCol_0()){
				int column = JUtil.strToInt(requestParameters.getiSortCol_0(), 0);
				if(column < 0){
					column = 0;
				}
				String mDataProp_ = mDataProp + "_"+ column;
				mDataProp_ = request.getParameter(mDataProp_);
				if(null!=mDataProp_){
					sort = (JUtil.camelToUnderline(mDataProp_) + " ")+(( null == requestParameters.getsSortDir_0()?"":requestParameters.getsSortDir_0()));
				}
			}
		}

		if (null != paging) {
			queryMap.put("page", paging);
		}
		if (null != sort) {
			queryMap.put("orderByClause", sort);
		}

		List<Map<String,Object>> resultListMap = null;
		//默认数据权限
		if(requestParameters.getV2hldghlcib0agugzgf0ysbhy2nlc3m()  ==0){
			SessionInfo sessionInfo  = (SessionInfo)JUtil.getSessionObject(request);
			//是否为超级管理员
			if(JUtil.isNULL(sessionInfo.getSysUser().getUserType()) || sessionInfo.getSysUser().getUserType() !=0){
				final	String filterColumn = requestParameters.getFilterColumn();//过滤列
				final List<Integer> userIds = sessionInfo.getAllowAccessToDataUserIds();
				if(null == userIds || userIds.isEmpty()){
					resultListMap = new ArrayList<Map<String,Object>> ();
				}else{
					String filterSql = MapperUtil.builderFilterCriteriaSql(filterColumn, sessionInfo.getAllowIds());
					queryMap.put("filterSql", filterSql);
					resultListMap  =  baseMapper.getDefaultHashMap(queryMap);
					if(null!=paging){
						int count = baseMapper.countDefaultHashMap(queryMap);
						paging.setCount(count);
					}
				}
			}else{
				//是超级管理员情况
				resultListMap  =  baseMapper.getDefaultHashMap(queryMap);
				if(null!=paging){
					int count = baseMapper.countDefaultHashMap(queryMap);
					paging.setCount(count);
				}
			}
		}else{
			//不加数据权限
			resultListMap  =  baseMapper.getDefaultHashMap(queryMap);
			if(null!=paging){
				int count = baseMapper.countDefaultHashMap(queryMap);
				paging.setCount(count);
			}
		}
		//TODO 后面修改优化方案
		//返回集合
		List returnList = new ArrayList();
		for (Map<String, Object> map : resultListMap) {
			returnList.add(MapUtils.toCamelCaseMap(map));
		}

		//					JSONArray array =  JSONArray.fromObject(returnList);
		//返回数据
		if(requestParameters.getComp() == 1){
			if(requestParameters.getIsNonPage()==0){
				return new NormalDatagrid(paging.getCount(), returnList);
			}
			return new NormalDatagrid(0, returnList);
		}else{
			if(requestParameters.getIsNonPage()==0){
				return new DataTableNormalDatagrid(new Datagrid(requestParameters.getsEcho(),paging.getCount(),paging.getCount(), returnList));
			}
			return new DataTableNormalDatagrid(new Datagrid(requestParameters.getsEcho(),0,0, returnList));
		}
	}

	/**
	 * 根据代理bean查询集合 根据方法自适配
	 * @return
	 * @throws Exception 
	 * @param requestParameters
	 * @param request
	 * @param mapper
	 *  @param listMethodName
	 *  @param countMethodName
	 */
	public Object  list (final RequestParameters requestParameters,HttpServletRequest request,Object mapper,String listMethodName,String countMethodName,QueryCallBack callBack) throws Exception {
		Page paging = null;
		if(requestParameters.getIsNonPage()==0){
			if(requestParameters.getComp() == 1){
				paging = Page.getInstance(requestParameters.getPage()-1,requestParameters.getRows());
			}else{
				paging = Page.getInstance_(requestParameters.getiDisplayStart(),requestParameters.getiDisplayLength());
			}
		}
		List returnList = queryList(paging,requestParameters,request,mapper,listMethodName,countMethodName);
		Object foot  = null;
		if(null!=callBack){
			foot = callBack.callBack(mapper);
		}
		if(requestParameters.getComp() == 1){
			if(requestParameters.getIsNonPage()==0){
				return new NormalDatagrid(paging.getCount(), returnList,foot);
			}
			return new NormalDatagrid(0, returnList,foot);
		}else{
			DataTableNormalDatagrid dtnd = null;
			if(requestParameters.getIsNonPage()==0){
				return new DataTableNormalDatagrid(new Datagrid(requestParameters.getsEcho(),paging.getCount(),paging.getCount(), returnList),foot);
			}
			return new DataTableNormalDatagrid(new Datagrid(requestParameters.getsEcho(),0,0, returnList),foot);
		}
	}

	/**
	 * 导出方法
	 * @return
	 * @throws Exception 
	 * @param requestParameters
	 * @param request
	 * @param mapper
	 *  @param listMethodName
	 *  @param countMethodName
	 */
	public List<Map<String,Object>>  list (final RequestParameters requestParameters,HttpServletRequest request,Object mapper,String listMethodName,String countMethodName,QueryCallBack callBack,Map<String,Object> formatMap) throws Exception {
		Page paging = null;
		if(requestParameters.getIsNonPage()==0){
			if(requestParameters.getComp() == 1){
				paging = Page.getInstance(requestParameters.getPage()-1,requestParameters.getRows());
			}else{
				paging = Page.getInstance_(requestParameters.getiDisplayStart(),requestParameters.getiDisplayLength());
			}
		}
		List<Map<String,Object>> returnList = queryList(paging,requestParameters,request,mapper,listMethodName,countMethodName,formatMap);
		if(null!=callBack){
			callBack.callExcelBack(mapper);
		}
		return returnList;
	}

	/**
	 * 根据代理bean查询集合 根据方法自适配
	 * @return
	 * @throws Exception 
	 * @param requestParameters
	 * @param request
	 * @param mapper
	 *  @param listMethodName
	 *  @param countMethodName
	 */
	public Object  list (final RequestParameters requestParameters,HttpServletRequest request,Object mapper,String listMethodName,String countMethodName) throws Exception {
		Page paging = null;
		if(requestParameters.getIsNonPage()==0){
			if(requestParameters.getComp() == 1){
				paging = Page.getInstance(requestParameters.getPage()-1,requestParameters.getRows());
			}else{
				paging = Page.getInstance_(requestParameters.getiDisplayStart(),requestParameters.getiDisplayLength());
			}
		}
		List returnList = queryList(paging,requestParameters,request,mapper,listMethodName,countMethodName);
		if(requestParameters.getComp() == 1){
			if(requestParameters.getIsNonPage()==0){
				return new NormalDatagrid(paging.getCount(), returnList);
			}
			return new NormalDatagrid(0, returnList);
		}else{
			if(requestParameters.getIsNonPage()==0){
				return new DataTableNormalDatagrid(new Datagrid(requestParameters.getsEcho(),paging.getCount(),paging.getCount(), returnList));
			}
			return new DataTableNormalDatagrid(new Datagrid(requestParameters.getsEcho(),0,0, returnList));
		}
	}

	private List queryList(Page paging,final RequestParameters requestParameters,HttpServletRequest request,Object mapper,String listMethodName,String countMethodName) throws Exception{
		Map<String,Object> queryMap = requestParameters.getQueryProxy();
		if(JUtil.isNULL(mapper)){
			throw new RuntimeException("传入的mapper为空!");
		}
		if(JUtil.isNULL(queryMap)){
			queryMap = new HashMap<String,Object>();
		}
		String sort = requestParameters.getSort();
		if(requestParameters.getComp() != 1){
			if(null != requestParameters.getiSortCol_0()){
				int column = JUtil.strToInt(requestParameters.getiSortCol_0(), 0);
				if(column < 0){
					column = 0;
				}
				String mDataProp_ = mDataProp + "_"+ column;
				mDataProp_ = request.getParameter(mDataProp_);
				if(null!=mDataProp_){
					sort = (JUtil.camelToUnderline(mDataProp_) + " ")+(( null == requestParameters.getsSortDir_0()?"":requestParameters.getsSortDir_0()));
				}
			}
		}

		if (null != paging) {
			queryMap.put("page", paging);
		}
		if (null != sort) {
			queryMap.put("orderByClause", sort);
		}
		//设置默认方法
		if(JUtil.isNull(listMethodName)){
			listMethodName = "getHashMap";
		}
		if(JUtil.isNull(countMethodName)){
			countMethodName = "countyHashMap";
		}

		Method listMethod = JUtil.getMethod(mapper.getClass(), listMethodName, Map.class);
		Method countMethod = JUtil.getMethod(mapper.getClass(), countMethodName, Map.class);

		List<Map<String,Object>> resultListMap = null;
		//默认数据权限
		if(requestParameters.getV2hldghlcib0agugzgf0ysbhy2nlc3m()  ==0){
			SessionInfo sessionInfo  = (SessionInfo)JUtil.getSessionObject(request);
			//是否为超级管理员
			if(JUtil.isNULL(sessionInfo.getSysUser().getUserType()) || sessionInfo.getSysUser().getUserType() !=0){
				final	String filterColumn = requestParameters.getFilterColumn();//过滤列
				final List<Integer> userIds = sessionInfo.getAllowAccessToDataUserIds();
				if(null == userIds || userIds.isEmpty()){
					resultListMap = new ArrayList<Map<String,Object>> ();
				}else{
					String filterSql = MapperUtil.builderFilterCriteriaSql(filterColumn, sessionInfo.getAllowIds());
					queryMap.put("filterSql", filterSql);
					resultListMap  =(List<Map<String, Object>>) listMethod.invoke(mapper, queryMap);
					if(null!=paging){
						Integer count = (Integer) countMethod.invoke(mapper, queryMap);
						paging.setCount(count);
					}
				}
			}else{
				//是超级管理员情况
				resultListMap  =(List<Map<String, Object>>) listMethod.invoke(mapper, queryMap);
				if(null!=paging){
					Integer count = (Integer) countMethod.invoke(mapper, queryMap);
					paging.setCount(count);
				}
			}
		}else{
			//不加数据权限
			resultListMap  =(List<Map<String, Object>>) listMethod.invoke(mapper, queryMap);
			if(null!=paging){
				Integer count = (Integer) countMethod.invoke(mapper, queryMap);
				paging.setCount(count);
			}
		}
		//TODO 后面修改优化方案
		//返回集合
		List returnList = new ArrayList();
		if(JUtil.isNULL(resultListMap) || resultListMap.isEmpty()){
			return returnList;
		}
		for (Map<String, Object> map : resultListMap) {
			returnList.add(MapUtils.toCamelCaseMap(map));
		}
		return returnList;
	}

	private List queryList(Page paging,final RequestParameters requestParameters,HttpServletRequest request,Object mapper,String listMethodName,String countMethodName,Map<String,Object> formatMap) throws Exception{
		Map<String,Object> queryMap = requestParameters.getQueryProxy();
		if(JUtil.isNULL(mapper)){
			throw new RuntimeException("传入的mapper为空!");
		}
		if(JUtil.isNULL(queryMap)){
			queryMap = new HashMap<String,Object>();
		}
		String sort = requestParameters.getSort();
		if(requestParameters.getComp() != 1){
			if(null != requestParameters.getiSortCol_0()){
				int column = JUtil.strToInt(requestParameters.getiSortCol_0(), 0);
				if(column < 0){
					column = 0;
				}
				String mDataProp_ = mDataProp + "_"+ column;
				mDataProp_ = request.getParameter(mDataProp_);
				if(null!=mDataProp_){
					sort = (JUtil.camelToUnderline(mDataProp_) + " ")+(( null == requestParameters.getsSortDir_0()?"":requestParameters.getsSortDir_0()));
				}
			}
		}

		if (null != paging) {
			queryMap.put("page", paging);
		}
		if (null != sort) {
			queryMap.put("orderByClause", sort);
		}
		//设置默认方法
		if(JUtil.isNull(listMethodName)){
			throw new RuntimeException("传入的查询方法为空!");
			//listMethodName = "getHashMap";
		}
		Method countMethod = null;
		if(!JUtil.isNull(countMethodName)){
			countMethod = JUtil.getMethod(mapper.getClass(), countMethodName, Map.class);
		}

		Method listMethod = JUtil.getMethod(mapper.getClass(), listMethodName, Map.class);


		List<Map<String,Object>> resultListMap = null;
		//默认数据权限
		if(requestParameters.getV2hldghlcib0agugzgf0ysbhy2nlc3m()  ==0){
			SessionInfo sessionInfo  = (SessionInfo)JUtil.getSessionObject(request);
			//是否为超级管理员
			if(JUtil.isNULL(sessionInfo.getSysUser().getUserType()) || sessionInfo.getSysUser().getUserType() !=0){
				final	String filterColumn = requestParameters.getFilterColumn();//过滤列
				final List<Integer> userIds = sessionInfo.getAllowAccessToDataUserIds();
				if(null == userIds || userIds.isEmpty()){
					resultListMap = new ArrayList<Map<String,Object>> ();
				}else{
					String filterSql = MapperUtil.builderFilterCriteriaSql(filterColumn, sessionInfo.getAllowIds());
					queryMap.put("filterSql", filterSql);
					resultListMap  =(List<Map<String, Object>>) listMethod.invoke(mapper, queryMap);
					if(null!=paging && null!= countMethod){
						Integer count = (Integer) countMethod.invoke(mapper, queryMap);
						paging.setCount(count);
					}
				}
			}else{
				//是超级管理员情况
				resultListMap  =(List<Map<String, Object>>) listMethod.invoke(mapper, queryMap);
				if(null!=paging && null!= countMethod){
					Integer count = (Integer) countMethod.invoke(mapper, queryMap);
					paging.setCount(count);
				}
			}
		}else{
			//不加数据权限
			resultListMap  =(List<Map<String, Object>>) listMethod.invoke(mapper, queryMap);
			if(null!=paging && null!= countMethod){
				Integer count = (Integer) countMethod.invoke(mapper, queryMap);
				paging.setCount(count);
			}
		}
		//TODO 后面修改优化方案
		//返回集合
		List returnList = new ArrayList();
		if(JUtil.isNULL(resultListMap) || resultListMap.isEmpty()){
			return returnList;
		}
		for (Map<String, Object> map : resultListMap) {
			if(JUtil.isNULL(map) || map.isEmpty()){
				continue;
			}
			returnList.add(MapUtils.toCamelCaseMap(map,formatMap));
		}
		return returnList;
	}

	/**
	 * 根据代理bean查询集合 根据方法自适配
	 * @return
	 * @throws Exception 
	 * @param requestParameters
	 * @param request
	 * @param mapper
	 *  @param listMethodName
	 *  @param countMethodName
	 */
	public Object  find (final RequestParameters requestParameters,HttpServletRequest request,Object mapper,String listMethodName) throws Exception {
		List<Map<String,Object>> returnList = list(requestParameters,request,mapper,listMethodName,null,null,null);
		if(JUtil.isNULL(returnList) || returnList.isEmpty()){
			return new JSONObject();
		}
		return returnList.get(0);
	}

	/**
	 * 根据代理bean查询集合 根据方法自适配
	 * @return
	 * @throws Exception 
	 * @param requestParameters
	 * @param request
	 * @param mapper
	 *  @param listMethodName
	 *  @param countMethodName
	 */
	public Object  findObject (final RequestParameters requestParameters,HttpServletRequest request,Object mapper,String methodName) throws Exception {

		Map<String,Object> queryMap = requestParameters.getQueryProxy();
		if(JUtil.isNULL(mapper)){
			throw new RuntimeException("传入的mapper为空!");
		}
		if(JUtil.isNULL(queryMap)){
			queryMap = new HashMap<String,Object>();
		}
		String sort = requestParameters.getSort();
		if(requestParameters.getComp() != 1){
			if(null != requestParameters.getiSortCol_0()){
				int column = JUtil.strToInt(requestParameters.getiSortCol_0(), 0);
				if(column < 0){
					column = 0;
				}
				String mDataProp_ = mDataProp + "_"+ column;
				mDataProp_ = request.getParameter(mDataProp_);
				if(null!=mDataProp_){
					sort = (JUtil.camelToUnderline(mDataProp_) + " ")+(( null == requestParameters.getsSortDir_0()?"":requestParameters.getsSortDir_0()));
				}
			}
		}

		if (null != sort) {
			queryMap.put("orderByClause", sort);
		}
		//设置默认方法
		if(JUtil.isNull(methodName)){
			throw new RuntimeException("传入的方法名为空!");
		}

		Method method = JUtil.getMethod(mapper.getClass(), methodName, Map.class);

		Map<String,Object> resultMap = null;
		//默认数据权限
		if(requestParameters.getV2hldghlcib0agugzgf0ysbhy2nlc3m()  ==0){
			SessionInfo sessionInfo  = (SessionInfo)JUtil.getSessionObject(request);
			//是否为超级管理员
			if(JUtil.isNULL(sessionInfo.getSysUser().getUserType()) || sessionInfo.getSysUser().getUserType() !=0){
				final	String filterColumn = requestParameters.getFilterColumn();//过滤列
				final List<Integer> userIds = sessionInfo.getAllowAccessToDataUserIds();
				if(null == userIds || userIds.isEmpty()){
					resultMap = new HashMap<String,Object>();
				}else{
					String filterSql = MapperUtil.builderFilterCriteriaSql(filterColumn, sessionInfo.getAllowIds());
					queryMap.put("filterSql", filterSql);
					resultMap  =(Map<String,Object>) method.invoke(mapper, queryMap);

				}
			}else{
				//是超级管理员情况
				resultMap  =(Map<String,Object>) method.invoke(mapper, queryMap);
			}
		}else{
			//不加数据权限
			resultMap  =(Map<String,Object>) method.invoke(mapper, queryMap);
		}
		//TODO 后面修改优化方案
		//返回集合
		List returnList = new ArrayList();
		if(JUtil.isNULL(resultMap) || resultMap.isEmpty()){
			return resultMap;
		}
		Map<String,Object> newRtnMap = MapUtils.toCamelCaseMap(resultMap,null);
		return newRtnMap;

	}
}
